<script setup>
import { ref, reactive, watch, toRaw } from 'vue';

import { getDevices, getGroups, createPoint } from "@/api/device";
import { pointRules } from "../utils/rules";

const visible = defineModel("visible")

const props = defineProps({
  no: {
    type: String
  },
  group: {
    type: String,
    default: null
  }
})

const emits = defineEmits(["update", "updateGroup"])

const funcs = ["M", "X", "Y", "D", "W", "L", "R"]

function resetData() {
  Object.assign(data, defaultData)
  data.no = props.no
  data.group = props.group
}
watch(() => props.no, resetData)
watch(() => props.group, resetData)

const defaultData = {
  no: "",
  group: "",
  name: "",
  func: "M",
  addr: "",
  desc: ""
}

const data = reactive({...defaultData})

// 获取可选设备列表
const devices = ref([])
getDevices().then(res => {
  if (res.code === 200) {
    devices.value = res.data.map(d => ({label: `${d.name}(${d.no})`, value: d.no}))
  }
})
// 设备可选分组
const groups = ref([])
watch(() => data.no, no => {
  if (no) {
    getGroups(no).then(res => {
      if (res.code === 200) {
        groups.value = res.data
      }
    })
  } else {
    Object.assign(data, defaultData)
    groups.value = []
  }
})

function groupDisplayChange() {
  if (data.no) {
    getGroups(data.no).then(res => {
      if (res.code === 200) {
        groups.value = res.data
      }
    })
  } else {
    groups.value = []
  }
}

// 表单dom对象，用于做数据校验
const formRef = ref()

function toCreatePoint() {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      createPoint(toRaw(data)).then(res => {
        if (res.code === 200) {
          ElMessage.success("创建成功")
          visible.value = false
          if (!groups.value.includes(data.group)) {
            emits("updateGroup")
          }
          emits("update", data.group)
        } else {
          ElMessage.error(res.msg)
        }
      }).catch(err => {
        console.log(err)
        ElMessage.error("网络异常，请稍后重试")
      })
    } else {
      ElMessage.error("请根据提示完善信息后再进行提交")
    }
  })
  
}
</script>

<template>
  <el-dialog title="创建点位" v-model="visible" width="480px">
    <el-form ref="formRef" :model="data" :rules="pointRules" label-width="72px">
      <el-form-item label="设备" prop="no">
        <el-select v-model="data.no">
          <el-option v-for="dev in devices" :label="dev.label" :value="dev.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="分组">
        <el-select 
          placeholder="选择现有分组或输入新分组"
          no-data-text="无可选分组"
          v-model="data.group" 
          @visible-change="groupDisplayChange" 
          allow-create filterable
        >
          <el-option v-for="group in groups" :label="group" :value="group" />
        </el-select>
      </el-form-item>
      <el-form-item label="点位" prop="addr">
        <el-input v-model="data.addr" placeholder="请输入点位地址">
          <template #prepend>
            <el-select v-model="data.func" placeholder="功能码" style="width: 96px">
              <el-option v-for="f in funcs" :label="f" :value="f" />
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="代号" prop="name">
        <el-input v-model="data.name" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input type="textarea" :rows="4" v-model="data.desc" />
      </el-form-item>
      <div class="btn-group">
        <el-button type="primary" @click="toCreatePoint()">创 建</el-button>
        <el-button @click="visible=false">取 消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">
.btn-group {
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>
